package com.ruirui.demo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class flatMap {
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Person {
        private String name;
        private int age;
        private List<House> houses;

        // 添加构造函数
    }
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class House {
        private String name;
        private List<Door> doors;
        // 添加构造函数
    }
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Door {
        private String name;
        // 添加构造函数
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Result {
        private String name;
        private  List<String> doorName;



        // 添加构造函数
    }

    public static void main(String[] args) {
        List<Door> doors = List.of(
                new Door("门1"),
                new Door("门2")
        );
        List<House> houses1 = List.of(
                new House("别墅", List.of(new Door("门1"), new Door("门2"))),
                new House("普通", List.of(new Door("门1")))
        );
        List<House> houses2 = List.of(
                new House("别墅", List.of(new Door("门1"))),
                new House("普通",  List.of(new Door("门2"))
        ));
        List<Person> persons = List.of(
                new Person("张三", 18, houses1),
                new Person("李四", 19, houses2),
                new Person("王五", 20, houses1)
        );
        // 查询大于18岁的人使用的门都是什么门
       persons.stream()
               .filter(person -> person.getAge() > 18)//只取满足条件的
               .flatMap(person ->
                        person.getHouses().stream().
                                flatMap(house -> house.getDoors().stream()))
               .peek(System.out::println)
               .distinct()
               .map(Door::getName)
               .collect(Collectors.toList())
               .forEach(System.out::println);
        // forEach(System.out::println)属于终止操作
        // ; peek是中间操作 可以在中间打印流的元素

        persons.stream()
                .takeWhile(person -> person.getAge() < 18)  // 不满足条件直接会结束
                .flatMap(person ->
                        person.getHouses().stream().
                                flatMap(house -> house.getDoors().stream()))
                .peek(System.out::println)
                .distinct()
                .map(Door::getName)
                .collect(Collectors.toList())
                .forEach(System.out::println);
    }
}
